import React from 'react';
import Api from 'Utils/api';
import './../../InformPage/index.scss';

class Recording extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      voiceState: this.props.voiceState,
      imgNmber: 1,
    };
    this.timer = null;
    this.voiceEnd = ::this.voiceEnd;
    this.voiceStart = ::this.voiceStart;
    this.recordHandle = ::this.recordHandle;
    this.getServerMediaId = ::this.getServerMediaId;
    this.getStorageFileId = ::this.getStorageFileId;
  }
  componentWillUnmount() {
    this.voiceEnd();
  }
  getStorageFileId(serverId) {
    const self = this;
    const api = new Api({
      method: 'GET',
      path: '/files/wechat',
      query: {
        server_id: serverId,
      },
      success: (json) => {
        self.props.getVoiceLocalId(json.id);
      },
    });
    api.run();
  }
  getServerMediaId(localId) {
    const self = this;
    wx.uploadVoice({
      localId, // 需要上传的音频的本地ID，由stopRecord接口获得
      isShowProgressTips: 1, // 默认为1，显示进度提示
      success(res) {
        self.getStorageFileId(res.serverId);
      },
    });
  }
  voiceStart() {
    const self = this;
    wx.startRecord({
      success: () => {
        self.setState({
          voiceState: true,
        }, () => {
          self.timer = setInterval(() => {
            const newVolume = this.state.imgNmber === 6 ? 1 : this.state.imgNmber + 1;
            self.setState({
              imgNmber: newVolume,
            });
          }, 500);
        });
      },
    });
  }
  voiceEnd() {
    const self = this;
    wx.stopRecord({
      success: (res) => {
        self.setState({
          voiceState: false,
        }, () => {
          clearInterval(self.timer);
          self.getServerMediaId(res.localId);
        });
      },
    });
  }
  recordHandle() {
    if (this.state.voiceState) {
      return this.voiceEnd();
    }
    return this.voiceStart();
  }
  render() {
    const { voiceState, imgNmber } = this.state;
    return (
      <div className="test-modal">
        <div className="voice-ui">
          <img src={`./images/icons/icon_audio${imgNmber}.png`} alt="停止录音" />
        </div>
        <div className="voice-button">
          <img
            onClick={this.recordHandle}
            src={`./images/icons/icon_audio_${voiceState ? 'pause' : 'record'}.png`}
            alt="录音按钮"
          />
        </div>
      </div>
    )
  }
}
export default Recording
